<script setup>
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import usePageTitle from '@/hooks/usePageTitle'
import useNavToLogin from '@/hooks/useNavToLogin'
import useGetBlogList from '@/hooks/useGetBlogList'
import ListPage from '@/components/ListPage.vue';
import { deleteBlog } from '@/api/blogApi';

const $router = useRouter()

useNavToLogin() // 未登录时跳转到登录页

usePageTitle('我的博客')

const { list, total, currentPage, pageSizeRef, getBlogListFn } = useGetBlogList({ my: true })

// 编辑博客，跳转到编辑页
const handleEdit = (blog) => {
    $router.push(`/blog/${blog.id}/edit`)
}

// 删除博客
const handleDelete = async (blog) => {
    // confirm 验证
    const confirm = await ElMessageBox.confirm('此操作将永久删除该博客, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
    if (confirm !== 'confirm') return

    try {
        await deleteBlog(blog.id)
        getBlogListFn() // 删除成功后重新获取博客列表
    } catch (error) {
        console.log(error)
    }
}
</script>

<template>
    <div class="title-container">
        <h2>我的博客</h2>
        <router-link to="/create">
            <el-button type="primary">创建博客</el-button>
        </router-link>
    </div>

    <!-- 用 table 显示博客列表，包括 title category likes favorites comments createdAt ，再加两个操作按钮“编辑” “删除” -->
    <el-table :data="list" border style="width: 100%">
        <!-- 标题列，点击标题链接到博客详情页 -->
        <el-table-column label="标题">
            <template #default="{ row }">
                <router-link :to="`/blog/${row.id}`">{{ row.title }}</router-link>
            </template>
        </el-table-column>
        <el-table-column prop="category" label="分类"></el-table-column>
        <el-table-column prop="likes" label="点赞数"></el-table-column>
        <el-table-column prop="favorites" label="收藏数"></el-table-column>
        <el-table-column prop="comments" label="评论数"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间"></el-table-column>
        <el-table-column label="操作">
            <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!--分页组件-->
    <ListPage :total="total" :currentPage="currentPage" :pageSizeRef="pageSizeRef" />
</template>

<style scoped>
.title-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
</style>